import Qs from 'qs';
import axios from 'axios';
import store from '@/store';

let errorCode = 500;
let errorCallback;
// 创建axios实例

const service = axios.create({
    // baseURL: 'http://hotfix.mxy.chinamobo.com/', // api的base_url
    timeout: 5000,                  // 请求超时时间
    withCredentials: true,   //加了这段就可以跨域了
    transformRequest: [function (data) {
        data = JSON.stringify(data);
        return data
    }],
});
// let apiPath = '/yii2/backend/index.php/'
// request拦截器
service.interceptors.request.use(config => {
    // Do something before request is sent
    if (store.getters.token) {
        //config.headers['X-Token'] = getToken(); // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    }
    config.headers['Accept'] = 'text/plain';
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    config.headers['Content-Type'] = 'application/json';
    const defaultParams = {
        // version: process.env.VERSION,
        platform: 'pcweb',
        token:'dbe3b094e9c35defd7909fc3c1b9ebb1'
    };
    // if(config.otherUrl){
    //     config.url = config.otherUrl + config.url;
    // } else {
    //     config.url = apiPath + config.url;
    //     console.log(config.url);
    // }
    if (config.method == 'post') {
        config.data = {
            ...defaultParams,
            ...config.data
        }
    } else if (config.method == 'get') {
        config.params = {
            ...defaultParams,
            ...config.params
        }
    }
    if (config.errorCode){
        errorCode = config.errorCode;
    }
    if (config.errorCallback){
        errorCallback = config.errorCallback;
    }
    return config;
}, error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
})

// respone拦截器
service.interceptors.response.use(
    response => {
        //console.log(response);
        const res = response.data;
        if (res.code !== 200) {
            if (res.code == 401 || res.code == 403){
                console.log('没有操作权限,请联系管理员');
            }
            // 登录过期了;
            else if (res.code == 403) {
                console.log('你已被退出');
            }else if (res.code == errorCode){
                console.log(res.msg);
                if (errorCallback){
                    errorCallback(res);
                }
            }else{
                return response;
            }
        } else {
            return response;
        }
    },
    error => {
        console.log('err' + error);// for debug
        if (error.response.status == 401){
            console.log('你已被退出');
        }else{
            console.log('抱歉~您没有访问和操作权限');
        }

        return Promise.reject(error);
    });

export default service;
